import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Meeting, Transcript, Minutes } from '@/types'
import { getMeetings, createMeeting, getMeeting, deleteMeeting, getMinutes } from '@/services/api'

export const useMeetingStore = defineStore('meeting', () => {
  // State
  const meetings = ref<Meeting[]>([])
  const currentMeeting = ref<Meeting | null>(null)
  const transcripts = ref<Transcript[]>([])
  const currentMinutes = ref<Minutes | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)

  // Getters
  const recentMeetings = computed(() =>
    meetings.value
      .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
      .slice(0, 5)
  )

  const meetingsByStatus = computed(() => {
    const grouped = {
      recording: [] as Meeting[],
      processing: [] as Meeting[],
      completed: [] as Meeting[],
    }

    meetings.value.forEach(meeting => {
      grouped[meeting.status].push(meeting)
    })

    return grouped
  })

  // Actions
  const fetchMeetings = async () => {
    loading.value = true
    error.value = null

    try {
      const response = await getMeetings()
      meetings.value = response.meetings || []
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取会议列表失败'
      console.error('Failed to fetch meetings:', err)
    } finally {
      loading.value = false
    }
  }

  const createNewMeeting = async (data: { title: string; description?: string }) => {
    loading.value = true
    error.value = null

    try {
      const response = await createMeeting(data)
      const meeting = response.meeting || response
      meetings.value.unshift(meeting)
      return response
    } catch (err) {
      error.value = err instanceof Error ? err.message : '创建会议失败'
      console.error('Failed to create meeting:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  const fetchMeeting = async (id: string) => {
    loading.value = true
    error.value = null

    try {
      const response = await getMeeting(id)
      const meeting = response.meeting
      currentMeeting.value = meeting

      // 获取转录内容
      if (meeting.transcription) {
        // 将后端的转录对象转换为前端期望的格式
        transcripts.value = [{
          id: meeting.transcription.meeting_id || '1',
          text: meeting.transcription.text || '',
          confidence: meeting.transcription.confidence || 0.95,
          timestamp: meeting.transcription.created_at || new Date().toISOString(),
          speaker: 'AI',
          word_timestamps: meeting.transcription.word_timestamps || [],
          language: meeting.transcription.language || 'chinese',
          word_count: meeting.transcription.word_count || 0
        }]
      }

      // 获取纪要内容
      if (meeting.minutes) {
        currentMinutes.value = meeting.minutes
      }

      return meeting
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取���议详情失败'
      console.error('Failed to fetch meeting:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  const fetchMinutes = async (meetingId: string) => {
    loading.value = true
    error.value = null

    try {
      const minutes = await getMinutes(meetingId)
      currentMinutes.value = minutes
      return minutes
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取纪要失败'
      console.error('Failed to fetch minutes:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  const removeMeeting = async (id: string) => {
    loading.value = true
    error.value = null

    try {
      await deleteMeeting(id)

      // 从列表中移除
      const index = meetings.value.findIndex(m => m.id === id)
      if (index > -1) {
        meetings.value.splice(index, 1)
      }

      // 如果是当前会议，清除
      if (currentMeeting.value?.id === id) {
        currentMeeting.value = null
        transcripts.value = []
        currentMinutes.value = null
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '删除会议失败'
      console.error('Failed to delete meeting:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  const clearError = () => {
    error.value = null
  }

  const updateMeetingStatus = (id: string, status: Meeting['status']) => {
    const meeting = meetings.value.find(m => m.id === id)
    if (meeting) {
      meeting.status = status
    }

    if (currentMeeting.value?.id === id) {
      currentMeeting.value.status = status
    }
  }

  const addTranscript = (transcript: Transcript) => {
    transcripts.value.push(transcript)
  }

  const updateMinutes = (minutes: Minutes) => {
    currentMinutes.value = minutes
  }

  return {
    // State
    meetings,
    currentMeeting,
    transcripts,
    currentMinutes,
    loading,
    error,

    // Getters
    recentMeetings,
    meetingsByStatus,

    // Actions
    fetchMeetings,
    createNewMeeting,
    fetchMeeting,
    fetchMinutes,
    removeMeeting,
    clearError,
    updateMeetingStatus,
    addTranscript,
    updateMinutes,
  }
})